const _ = require('../utils')
const { listParentBehavior, formItemBehavior } = require('../behaviors')

_.create('radio-group', {
  properties: {
    label: String,
    disabled: Boolean,
    bordered: { type: Boolean, value: false },
    helperText: {
      type: String,
      value: '',
    },
  },

  behaviors: ['wx://form-field', listParentBehavior, formItemBehavior],

  relations: {
    '../radio/index': {
      type: 'child',
      linked() {
        this.assignElementSN('../radio/index')
      },
      linkChanged() {
        this.assignElementSN('../radio/index')
      },
      unlinked() {
        this.assignElementSN('../radio/index')
      },
    },

    '../form-validator/index': {
      type: 'ancestor',
    },
  },

  observes: {
    value: function (v) {
      this.updateByValue(v)
    },
  },

  lifetimes: {
    ready() {
      this.updateByValue(this.data.value)
    },
  },

  methods: {
    onChecked(e) {
      const { index } = e.detail
      const radios = this.getRelationNodes('../radio/index') || []

      radios.forEach((r, i) => {
        const checked = i === index
        r.setChecked(checked)
        if (checked) {
          this.setData({
            value: r.data.value || r.data.label,
          })
        }
      })
    },

    updateByValue(v) {
      const radios = this.getRelationNodes('../radio/index') || []

      radios.forEach((r) => r.setChecked(v === (r.data.value || r.data.label)))
    },
  },
})
